/*
 * Copyright 2004-2008 the Seasar Foundation and the Others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package com.andybest.search.action;

import java.util.ArrayList;
import java.util.List;

import net.arnx.jsonic.JSON;

import org.seasar.struts.annotation.Execute;
import org.seasar.struts.util.ResponseUtil;

import com.andybest.search.dto.TaskInfo;
import com.andybest.search.timer.TaskListManager;
import com.andybest.search.util.SearchUtils;

public class SearchAction {

	public String itemName;

	public String taskId;

	public String searchType;

	public String minPrice;

	public String maxPrice;

	public String ngKeyword;

	public String email;

	@Execute(validator = false)
	public String index() {
		return "search.jsp";
	}

	@Execute(validator = false)
	public String addTask() {
		TaskInfo taskInfo = new TaskInfo();
		taskInfo.setTaskId(SearchUtils.createTaskId());
		taskInfo.setItemName(itemName);
		taskInfo.setActive(true);
		if(minPrice!=null&&!minPrice.equals(""))
		taskInfo.setMinPrice(Long.parseLong(minPrice));
		if(maxPrice!=null&&!maxPrice.equals(""))
		taskInfo.setMaxPrice(Long.parseLong(maxPrice));
		taskInfo.setNgKeyword(ngKeyword);
		taskInfo.setEmail(email);
		taskInfo.setSearchType(searchType);

		TaskListManager.getTaskList().add(taskInfo);
		ResponseUtil.write("{success:true}");
		return null;
	}

	@Execute(validator = false)
	public String doRemoveTask() {
		for (int i = 0; i < TaskListManager.getTaskList().size(); i++) {
			TaskInfo current = TaskListManager.getTaskList().get(i);
			if (current.getTaskId().equals(taskId)) {
				current.setActive(false);
			}
		}

		ResponseUtil.write("{success:true}");
		return null;
	}

	@Execute(validator = false)
	public String doGetTaskList() {
		List<TaskInfo> resultList = new ArrayList<TaskInfo>();
		for(TaskInfo current:TaskListManager.getTaskList()){
			if(current.getSearchType().equals(searchType)){
				resultList.add(current);
			}
		}
		ResponseUtil.write("{totalCount:\"" + 10 + "\",results:"
				+ JSON.encode(resultList) + "}");
		return null;
	}

}
